const config = require('../config')
const axios = require('axios')
import {Message} from 'element-ui'
import vue from '../../src/main'
import {showLoading, hideLoading } from './loading'

//网络错误码
function err(code){
    switch (code) {
        case 200:
            return true;
        case 400:
            Message.error('错误请求')
            break;
        case 401:
            Message.error('未授权,请重新登录')
            break;
        case 403:
            Message.error('拒绝访问')
            break;
        case 404:
            Message.error('请求错误,未找到该资源')
            break;
        case 405:
            Message.error('请求方法未允许')
            break;
        case 408:
            Message.error('请求超时')
            break;
        case 500:
            Message.error('服务器出错')
            break;
        case 501:
            Message.error('网络未实现')
            break;
        case 502:
            Message.error('网络出错')
            break;
        case 503:
            Message.error('服务不可用')
            break;
        case 504:
            Message.error('网络超时')
            break;
        case 505:
            Message.error('http版本不支持该请求')
            break;
        default:
            Message.error(`连接错误${error.response.status}`)
    }
    return
}

function getv(url,data,method){
    //获取全部接口数据
    var init = JSON.parse(window.localStorage.getItem('init'))
    //请求接口的所有版本
    var reqinit = []
    for (const i in init) {
        if (init[i].action != '' && url.includes(init[i].action)) {
            reqinit.push(init[i])
        }
    }
    //版本去除v后的数据
    var editionlist = []
    reqinit.forEach(item=>{
        editionlist.push(item.edition.substring(1,item.edition.length))
    })
    //从大到小排序
    var ddx = editionlist.sort((a,b)=>{
        return b-a;
    })
    //最新版本在所有请求接口版本的位置
    var endeditionindex = editionlist.findIndex(item=>{
        return item == ddx[0]
    })
    //拼接
    url = url + '_v' + ddx[0];

    //默认能发送请求
    var canSend = true
    //默认不能发送请求的原因为空
    var noneData = []
    if (reqinit[endeditionindex].must && reqinit[endeditionindex].must != null) {
        if (reqinit[endeditionindex].must.includes('token') && method == 'get') {
            //需要传token的将token加到传递的参数中
            data.token=config.get('userInfo').token
        }
        //将必须的传参转为数组
        var must = reqinit[endeditionindex].must.split(',')
        for (const i in must) {
            if (must[i] == 'token') {
                must.splice(i,1)
            }
        }
        //如果must不为空
        if (must!=null) {
            must.forEach(item=>{
                //如果用户传递的参数包含must 那么能发送请求
                if (data[item]) {
                    canSend = true
                }else{
                    //如果不包含 将信息加入到不能请求的原因中
                    noneData.push(item)
                    //不能发送请求
                    canSend = false
                }
            })
        }
    }
    return {
            url:url,
            index:endeditionindex,
            cansend:canSend,
            noneData:noneData,
            data:data
        }
}

//get请求
export const get = function(url,data,callback){
    var uurl = url
    var urin = getv(url,data,'get')
    url = urin.url
    if (urin.cansend) {
        var xmlget = new XMLHttpRequest()
        //定义数组保存请求时传的参数
        var str = []
        for(let i in urin.data){
            str.push(i + '=' + urin.data[i])
        }
        //将参数数组转为字符串并用& 拼接
        str = str.join('&')
        //拼接url
        url = config.get('app_url') + url + '?' + str
        xmlget.open('get',url,true)
        //发送请求
        xmlget.send()
        //获取加载动画节点
        var load = document.getElementById('loading')
        //显示加载动画
		showLoading();
        load?load.className = 'block':''
        xmlget.onreadystatechange = function(){
            //请求完成
            if(xmlget.readyState == 4){
                //隐藏加载动画
				hideLoading();
                load?load.className = 'loadnone':''
                //请求返回的状态码
                err(xmlget.status)
                if(xmlget.status == 200){
                    var resdata = JSON.parse(xmlget.responseText)
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 200:
                            break;
                        case 201:
                            Message.error(resdata.data)
                            break;
                        case 401:
                            axios.get(config.get('a_url')+'/checkoutLoginType?key='+config.get('userInfo').key+'&sertype=1')
                            .then(res=>{
                                if (res.data.code==200) {
                                    get('/index/index/login',{key:res.data.data.key},res=>{
                                        config.setUserInfo(res.data);
                                        get(uurl,data,res=>{
                                                callback(res)
                                        })
                                    })
                                } else {
                                    Message.error('登录信息失效,请重新登录')
                                    window.localStorage.clear()
                                    window.sessionStorage.clear()
                                    config.clear()
                                    vue.$router.push('/login')
                                }
                            })
                            break;
                        case 499:
                            Message.error('未授权')
                            break   
                        default:
                            Message.error(resdata.data)
                            break;
                        }
                    callback(resdata)
                }
            } 
        }   
    }else{
        Message.error('缺少参数'+urin.noneData)
    }
}

//post请求
export const post = function(url,data,callback){
    var uurl = url
    if (data.params) {
        var urin = getv(url,data.params,'post')
    }else{
        var urin = getv(url,data,'post')
    }
    url = urin.url+'?token='+config.get('userInfo').token
    if (urin.cansend) {
        var xmlpost = new XMLHttpRequest()
        url = config.get('app_url') + url
        xmlpost.open('post',url,true)
        if(data.header){
            for (let i in data.header) {
                xmlpost.setRequestHeader(i,data.header[i]);
            }
        }
        console.log(urin.data)
        xmlpost.send(urin.data)
        var load = document.getElementById('loading')
        
        load?load.className = 'block':''
        xmlpost.onreadystatechange = function(){
            if(xmlpost.readyState == 4){
                load?load.className = 'loadnone':''
                err(xmlpost.status)
                if(xmlpost.status == 200){
                    var resdata = JSON.parse(xmlpost.responseText)
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 201:
                            Message.error(resdata.data)
                            break;
                        case 401:
                            axios.get(config.get('a_url')+'/checkoutLoginType?key='+config.get('userInfo').key+'&sertype=1')
                            .then(res=>{
                                if (res.data.code==200) {
                                    get('/index/index/login',{key:res.data.data.key},res=>{
                                        config.setUserInfo(res.data);
                                        console.log(config.get('userInfo').token)
                                        post(uurl,data,res=>{
                                                callback(res)
                                        })
                                    })
                                } else {
                                    Message.error('登录信息失效,请重新登录')
                                    window.localStorage.clear()
                                    window.sessionStorage.clear()
                                    config.clear()
                                    vue.$router.push('/login')
                                }
                            })
                            break;
                        case 499:
                            Message.error('未授权')
                            break   
                        default:
                            callback(resdata)
                            break;
                    }
                }
            }
        }
    }else{
        Message.error('缺少参数'+urin.noneData)
    }
}


